<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router';
import { articleHeatService, articleCountService, articleListService, articleAddService, articleUpdateService, articleDeleteService } from '@/api/article';
const router = useRouter();
import {
    Search,
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { getHidAndComment, HitUpdateService, CommentsUpdateService, statisticListService } from '@/api/statistic';
import { ElMessage, ElMessageBox } from 'element-plus'
import { userKey } from '@/api/user.js';
import { useTokenStore } from '@/stores/token.js';
import { userKeyStore } from '@/stores/key.js';
const tokenSrore = useTokenStore();
const keyStore = userKeyStore();
// 加入看板娘
const initLive2DWidget2 = () => {
    // kobayaxi 康娜模型   sagiri  纱雾模型
    const name = "kobayaxi";
    const leimu = './live2dw/leiMu/11.json';
    const nilu = './live2dw/niLu/17.json'
    const violet = './live2dw/violet/14.json'
    setTimeout(() => {
        window.L2Dwidget.init({
            //设置Live2D插件的根路径
            pluginRootPath: 'live2dw/',
            // 插件的JavaScript文件路径设
            pluginJsPath: 'lib/',
            // 模型资源的相对路径设
            // pluginModelPath: name + '/',
            pluginModelPath: 'leimu' + '/',
            //表示使用标签模式
            tagMode: true,
            //关闭调试信息输出
            debug: false,
            //指定模型文件的路径
            model: {
                // 模型文件路径
                // jsonPath: './live2dw/' + name + '/model/' + name + '/' + name + '.model.json',
                jsonPath: leimu,
                scale: 0.7 //模型缩放比例
            },
            //配置模型展示的位置
            display: {
                position: "right", //模型的位置（左or右）
                width: 300, //模型宽度
                height: 600, //模型高度
                hOffset: -40, //模型水平偏移量
                vOffset: -160 //模型垂直偏移量
            },
            // 允许移动端展示
            mobile: {
                show: true
            },
            // 禁用日志输出
            log: false
        });
    }, 2000);
};
// 定义文章变量
const article = ref([
    {
        id: 2,
        title: "securit入门",
        category: "编程",
        thumbnail: "http://sem8jxmog.hn-bkt.clouddn.com/828ede11-8e20-4a36-afea-1bb983b3e94e.png",
        tag: "",
        content: "",
        hit: 10,
        commentNum: 22,
        createTime: "2023-09-02 12:06:59",
    }
])
// 定义最新文章变量
const articleNew = ref([
    {
        id: 2,
        title: "securit入门",
        category: "编程",
        thumbnail: "http://sem8jxmog.hn-bkt.clouddn.com/828ede11-8e20-4a36-afea-1bb983b3e94e.png",
        tag: "",
        content: "",
        hit: "12",
        createTime: "2023-09-02 12:06:59",
    }
])
//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(5)//每页条数
//导入用户登录图片
import loginPic from '@/assets/loginPic.png';
//导入用户退出图片
import logoutPic from '@/assets/logout.png';
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    // 将获取文章数据需要的参数更改为当前所需之后更新页面
    pageSize.value = size;
    articleList();
}

//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num;
    articleList();
}
// 定义个count来接受文章量
const count = ref(10);
const articleCount = async () => {
    //调用接口获取文章总数之后将其赋给count
    let result = await articleCountService();
    count.value = result.data;
}
articleCount()

// 获取所有文章
const articleList = async () => {
    //在首次进到首页也需要将其用户身份标识存到pinia中，否则便拿不到用户权限
    //当处于登录状态的时候才进行
    if (tokenSrore.token) {
        let key = await userKey();
        keyStore.setKey(key.data);
    }
    //定制文章列表分页查询参数
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
    }
    let result = await articleListService(params);
    console.log(result)
    total.value = result.data.total;
    article.value = result.data.items;
    //对每篇文章进行其浏览量的查询
    for (let i = 0; i < article.value.length; i++) {
        //遍历拿到的文章列表，然后拿到文章id，然后便可以得到文章统计数据
        let art = article.value[i];
        console.log("遍历拿到的文章id:" + art.id);
        let statistic = await getHidAndComment(art.id);
        // 拿到统计数据之后将其赋值给文章列表中的hit
        article.value[i].hit = statistic.data.hit;
        article.value[i].commentNum = statistic.data.commentNum;
        console.log("遍历前拿到的文章浏览量:" + statistic.data.hit);
        console.log("遍历后拿到的文章浏览量:" + article.value[i].hit);
    }
}
articleList()
// 绑定登录跳转事件
const login = () => {
    router.push('/login')
    ElMessage.success('请进行登录！');
}

// 实现获取最新消息
const getNewArticle = async () => {
    let result = await articleHeatService();
    articleNew.value = result.data;
}
// 刷新页面数据
getNewArticle();
articleList()
//定义变量绑定注册与头像切换

// 绑定跳转后台管理页面事件
const manage = () => {
    //首先先根据当前状态，如果已经登录，那么就进行身份判断
    if (tokenSrore.token) {
        //进行身份验证，因此在后台对用户权限进行了校验，只有用户存进的pinia中的isAdmin为真说明为管理员，否则为一般用户
        if (keyStore.key === 'true') {
            console.log('查看当前用户的身份信息：' + keyStore.key);
            ElMessage.success('欢迎来到后台系统，管理员')
            router.push('/main');
        } else {
            ElMessage.success('没有权限进行该操作')
            router.push('/');
        }
    } else {
        //如果没有登录，那么直接给放行，后台会自动给进行拦截
        router.push('/main');
    }
}
//绑定首页退出登录事件
const logout = () => {
    ElMessage.success('退出登录');
    // 清空pinia库数据以及跳转到首页页面
    tokenSrore.removeToken();
    userInfoStore.removeInfo();
    userKeyStore.removeKey();
    router.push('/');
}
initLive2DWidget2();
</script>

<template>
    <div>
        <!-- 导航 -->
        <nav class="ui inverted attached segment m-padded-tb-mini">
            <div class="ui container">
                <div class="ui inverted secondary menu">
                    <h2 class="ui teal header item">Blog-System</h2>
                    <a href="/" class="item"><i class="home icon"></i>首页</a>
                    <a href="#" class="item"><i class="idea icon"></i>分类</a>
                    <a href="#" class="item"><i class="tags icon"></i>标签</a>
                    <a href="#" class="item"><i class="info icon"></i>关于</a>
                    <div class="right item">
                        <div class="ui icon input">
                            <input type="text" placeholder="Search...."></input>
                            <i class="search icon"></i>
                        </div>
                        <span> </span><span> </span>
                        <!-- <a href="#" class="item" @click="arrLogin()">登录 注册</a> -->
                        <img v-if="tokenSrore.token" :src="logoutPic" class="avatar" @click="logout()"
                            style="max-width: 60px;width: 60px;margin-left: 15px;" />
                        <img v-else :src="loginPic" width="278" @click="login()"
                            style="max-width: 60px;width: 60px;margin-left: 15px;" />
                    </div>
                    <a href="#" class="item" @click="manage()"><i class="user icon"></i>后台管理</a>
                </div>
            </div>
        </nav>

        <!--  中间部分  -->
        <div class="container m-padded-tb-large">
            <div class="ui container">
                <div class="ui stackable grid">

                    <!-- left 博客列表 -->
                    <div class="eleven wide column">
                        <!-- header -->
                        <div class="ui attached segment">
                            <div class="ui middle aligned two column grid">
                                <div class="column">
                                    <h3 class="ui teal header">博客</h3>
                                </div>
                                <div class="right aligned column">
                                    共<h3 class="ui orange header m-text-thin m-inline-block">{{ count }}</h3>篇
                                </div>
                            </div>
                        </div>
                        <!-- content -->
                        <!-- 遍历获取所有文章信息 -->
                        <li v-for="(item, index) in article" :key="index">
                            <div class="ui attached segment">
                                <div style="padding: 0 1.2em" class="ui vertical segment m-padded-tb-large">
                                    <div class="ui mobile reversed stackable grid">
                                        <div class="eleven wide column">
                                            <h3 class="ui header">{{ item.title }}</h3>
                                            <h4>
                                                {{ item.content }}
                                            </h4>
                                            <div class="ui grid">
                                                <div class="eleven wide column">
                                                    <div class="ui mini horizontal link list">
                                                        <div class="item">
                                                            <img src="https://picsum.photos/id/1/100/100" alt=""
                                                                class="ui avatar image">
                                                            <div class="content"><a href="#" class="header">喜多川</a>
                                                            </div>
                                                        </div>
                                                        <div class="item">
                                                            <i class="calendar icon"></i>
                                                            <!-- 文章创建时间 -->
                                                            {{ item.createTime }}
                                                        </div>
                                                        <div class="item">
                                                            <!-- 文章点击量 -->
                                                            <i class="eye icon"></i>
                                                            {{ item.hit }}
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="five wide column">
                                                    <a href="#" target="_blank"
                                                        class="ui teal basic label m-padded-mini m-text-thin">认知升级</a>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="five wide column">
                                            <span href="" target="_blank">
                                                <!-- 绑定文章封面 -->
                                                <img :src="item.thumbnail" alt="" class="ui rounded image">
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </li>

                        <!-- footer -->
                        <div class="ui bottom attached segment">
                            <!-- 分页条 -->
                            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize"
                                :page-sizes="[3, 5, 10, 15]" layout="total, sizes, prev, pager, next" background
                                :total="total" @size-change="onSizeChange" @current-change="onCurrentChange"
                                style="margin-top: 20px; justify-content: flex-end" />
                        </div>
                    </div>
                    <!-- right card卡片 -->
                    <div class="five wide column">

                        <!-- 分类 -->
                        <div class="ui segments">
                            <div class="ui secondary segment">
                                <div class="ui two column grid">
                                    <div class="column">
                                        <i class="idea icon"></i>分类
                                    </div>
                                    <div class="right aligned column">
                                        <a href="#" target="_blank">more <i class="angle double right icon"></i></a>
                                    </div>
                                </div>
                            </div>
                            <div class="ui teal segment">
                                <div class="ui fluid vertical menu">
                                    <!-- 分类模块 -->
                                    <li v-for="(item, index) in article" :key="index">
                                        <a href="#" class="item"> {{ item.category }} <div
                                                class="ui teal basic left pointing label">
                                                {{ item.hit }}
                                            </div></a>
                                    </li>
                                </div>
                            </div>
                        </div>
                        <!-- 标签 -->
                        <div class="ui segments">
                            <div class="ui secondary segment">
                                <div class="ui two column grid">
                                    <div class="column">
                                        <i class="tags icon"></i>标签
                                    </div>
                                    <div class="right aligned column">
                                        <a href="#" target="_blank">more <i class="angle double right icon"></i></a>
                                    </div>
                                </div>
                            </div>
                            <div class="ui teal segment">
                                <!-- 便签模块 -->
                                <li v-for="(item, index) in article" :key="index">
                                    <a href="#" target="_blank"
                                        class="ui teal basic left pointing label m-padded-tb-tiny m-margin-tb-tiny">
                                        {{ item.tag }}
                                        <div class="detail">{{ item.commentNum }}</div></a>
                                </li>
                            </div>
                        </div>

                        <!-- 最新推荐 -->
                        <div class="ui segments m-margin-top-large">
                            <div class="ui secondary segment">
                                <i class="bookmark icon"></i>最新推荐
                            </div>
                            <li v-for="(non, index) in articleNew" :key="index">
                                <div class="ui segment">
                                    <span target="_blank" class=" m-black m-text-thin">{{ non.title }}</span>
                                </div>
                            </li>

                        </div>

                        <!-- QR -->
                        <h4 class="ui horizontal divider header m-margin-top-large">扫码关注</h4>
                        <div class="ui centered card" style="width: 10em;">
                            <img src="http://sem8jxmog.hn-bkt.clouddn.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20240620003656.jpg"
                                alt="" class="ui rounded image">
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<style lang="scss" scoped>
//导入其样式
@import url('https://cdn.jsdelivr.net/semantic-ui/2.2.10/semantic.min.css');

// 清除列表标点
li {
    list-style-type: none;
}
</style>